package com.quanyan.place.security.shiro;

import com.google.common.collect.Sets;

import com.quanyan.api.APIResponse;
import com.quanyan.common.exception.BizException;
import com.quanyan.place.entity.TbAdminUser;
import com.quanyan.place.entity.TbAdminUserExample;
import com.quanyan.place.mapper.TbAdminUserMapper;
import com.quanyan.place.mapper.UserMapper;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * @Author Hugo.Wwg
 * @Since 2016-04-13
 */
@Component
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private TbAdminUserMapper adminUserMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        Set<String> roles = Sets.newHashSet();
        roles.add("manager");

        Set<String> permissions = Sets.newHashSet();
        permissions.add("add");

        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(permissions);

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String loginName = upToken.getUsername();

        TbAdminUserExample example = new TbAdminUserExample();
        example.createCriteria().andLoginNameEqualTo(loginName);
        List<TbAdminUser> adminUserList = adminUserMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(adminUserList)) {
            throw new BizException("用户不存在");
        }

        TbAdminUser tbAdminUser = adminUserList.get(0);
        //通常这里对用户名和密码进行校验,这里就省略了
        String password = tbAdminUser.getPassword();
        return new SimpleAuthenticationInfo(loginName,  password.toCharArray(), getName());
    }
}
